﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Xml;

namespace OF.Utility
{
    public class SendMessage
    {
        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="smsContent">短信内容</param>
        /// <param name="strMobile">手机号，如果是多个手机号，请用逗号隔开</param>
        /// <param name="msg">错误信息</param>
        /// <returns></returns>
        public static bool SendMsg(string smsContent, string strMobile, out string msg)
        {
            Encoding apiEncoding = Encoding.UTF8;
            string url = string.Format("{0}/sms/SendShortMessage?mobile={1}&content={2}&platformId=1", SiteUtility.GetAppSettings("SMSUrl"), strMobile, smsContent);
            msg = "";
            return RequestHelper.GetHtml(url, "get", apiEncoding, out msg, 2000);
        }


        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="smsContent">短信内容</param>
        /// <param name="strMobile">手机号，如果是多个手机号，请用逗号隔开</param>
        /// <param name="msg">错误信息</param>
        /// <returns></returns>
        public static bool SendServiceMsg(string smsContent, string strMobile, out string msg)
        {
            Encoding apiEncoding = Encoding.UTF8;
            string url = string.Format("{0}/sms/SendServiceShortMessage?mobile={1}&content={2}&platformId=1", SiteUtility.GetAppSettings("SMSUrl-Service"), strMobile, smsContent);
            msg = "";
            return RequestHelper.GetHtml(url, "get", apiEncoding, out msg, 2000);
           
        }
        ///// <summary>
        ///// 发送短信
        ///// </summary>
        ///// <param name="smsContent">短信内容</param>
        ///// <param name="strMobile">手机号，如果是多个手机号，请用逗号隔开</param>
        ///// <param name="msg">错误信息</param>
        ///// <returns></returns>
        //public static bool SendMsg(string smsContent, string strMobile, out string msg)
        //{
        //    string targetUrl = ConfigurationManager.AppSettings["SMSUrl"];
        //    string userId = ConfigurationManager.AppSettings["SMSAccount"];
        //    string userPwd = ConfigurationManager.AppSettings["SMSPassWord"];

        //    string noteContent = System.Web.HttpUtility.UrlEncode(smsContent);

        //    targetUrl += "/MongateSendSubmit?userId=" + userId + "&password=" + userPwd + "&pszMobis=" + strMobile + "&pszMsg=" + noteContent + "&iMobiCount=1&pszSubPort=*&MsgId=1789";

        //    var request = WebRequest.Create(targetUrl) as HttpWebRequest;
        //    if (request != null)
        //    {
        //        request.Method = "GET";

        //        //获取服务器返回的资源  
        //        using (var response = (HttpWebResponse)request.GetResponse())
        //        {
        //            using (var reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")))
        //            {
        //                string resultStr = reader.ReadToEnd();

        //                XmlDocument xmlDoc = new XmlDocument();
        //                xmlDoc.LoadXml(resultStr);
        //                //XmlNode msgNode = xmlDoc.SelectSingleNode("string");
        //                msg = xmlDoc?.InnerText ?? "";
        //                //发送失败：返回的字符串长度小于15表示发送失败
        //                if (msg.Length < 15)
        //                {
        //                    return false;
        //                }
        //                return true;
        //            }
        //        }
        //    }
        //    else
        //    {
        //        msg = "发送短信失败，接口连接失败，请联系管理员";
        //        return false;
        //    }
        //}

        ///// <summary>
        ///// 发送短信
        ///// </summary>
        ///// <param name="smsContent">短信内容</param>
        ///// <param name="strMobile">手机号，如果是多个手机号，请用逗号隔开</param>
        ///// <param name="msg">错误信息</param>
        ///// <returns></returns>
        //public static bool SendServiceMsg(string smsContent, string strMobile, out string msg)
        //{
        //    string targetUrl = ConfigurationManager.AppSettings["SMSUrl-Service"];
        //    string userId = ConfigurationManager.AppSettings["SMSAccount-Service"];
        //    string userPwd = ConfigurationManager.AppSettings["SMSPassWord-Service"];

        //    string noteContent = System.Web.HttpUtility.UrlEncode(smsContent);
        //    string[] mobileArray = strMobile.Split(new []{ ','}, StringSplitOptions.RemoveEmptyEntries);
        //    targetUrl += "/MongateSendSubmit?userId=" + userId + "&password=" + userPwd + "&pszMobis=" + strMobile + "&pszMsg=" + noteContent + "&iMobiCount="+ mobileArray .Length+ "&pszSubPort=*&MsgId=1789";

        //    Encoding myEncoding = Encoding.GetEncoding("gb2312");
        //    string param =
        //        HttpUtility.UrlEncode("userId", myEncoding) +
        //        "=" + HttpUtility.UrlEncode(userId, myEncoding) +
        //        "&" + HttpUtility.UrlEncode("password", myEncoding) +
        //        "=" + HttpUtility.UrlEncode(userPwd, myEncoding) +
        //        "&" + HttpUtility.UrlEncode("pszMobis", myEncoding) +
        //        "=" + HttpUtility.UrlEncode(strMobile, myEncoding) +
        //        "&" + HttpUtility.UrlEncode("pszMsg", myEncoding) +
        //        "=" + HttpUtility.UrlEncode(noteContent, myEncoding) +
        //        "&" + HttpUtility.UrlEncode("iMobiCount", myEncoding) +
        //        "=" + HttpUtility.UrlEncode(mobileArray.Length.ToString(), myEncoding) +
        //        "&" + HttpUtility.UrlEncode("pszSubPort", myEncoding) +
        //        "=" + HttpUtility.UrlEncode("*", myEncoding) +
        //        "&" + HttpUtility.UrlEncode("MsgId", myEncoding) +
        //        "=" + HttpUtility.UrlEncode("1789", myEncoding)   ;

        //    var request = WebRequest.Create(targetUrl) as HttpWebRequest;

        //    if (request != null)
        //    {
        //        request.Method = "get";

        //        //获取服务器返回的资源  
        //        using (var response = (HttpWebResponse)request.GetResponse())
        //        {
        //            using (var reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")))
        //            {
        //                string resultStr = reader.ReadToEnd();

        //                XmlDocument xmlDoc = new XmlDocument();
        //                xmlDoc.LoadXml(resultStr);
        //                //XmlNode msgNode = xmlDoc.SelectSingleNode("string");
        //                msg = xmlDoc?.InnerText ?? "";
        //                if (msg.Length <= 15)
        //                {
        //                    //发送失败 log
        //                    return false;
        //                }
        //                return true;
        //            }
        //        }
        //    }
        //    else
        //    {
        //        msg = "发送短信失败，接口连接失败，请联系管理员";
        //        return false;
        //    }
        //}

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="smsContent">短信内容</param>
        /// <param name="strMobile">手机号，如果是多个手机号，请用逗号隔开</param>
        /// <param name="msg">错误信息</param>
        /// <returns></returns>
        public static bool SendServiceMsgPost(string smsContent, string strMobile, out string msg)
        {
            try
            {
                string targetUrl = ConfigurationManager.AppSettings["SMSUrl-Service"];
                string userId = ConfigurationManager.AppSettings["SMSAccount-Service"];
                string userPwd = ConfigurationManager.AppSettings["SMSPassWord-Service"];

                string noteContent = System.Web.HttpUtility.UrlEncode(smsContent);
                string[] mobileArray = strMobile.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries);
                targetUrl += "/MongateSendSubmit";

                string param = "?userId=" + userId + "&password=" + userPwd + "&pszMobis=" + strMobile + "&pszMsg=" +
                               noteContent + "&iMobiCount=" + mobileArray.Length + "&pszSubPort=*&MsgId=1789";

                HttpWebRequest request = (HttpWebRequest) WebRequest.Create(targetUrl);
              
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.Accept = "*/*";
                request.Headers.Add("Accept-Encoding: gzip,deflate");
                request.Headers.Add("Accept-Language: zh-cn");

                //string param =
                //    HttpUtility.UrlEncode("userId", myEncoding) +
                //    "=" + HttpUtility.UrlEncode(userId, myEncoding) +
                //    "&" + HttpUtility.UrlEncode("password", myEncoding) +
                //    "=" + HttpUtility.UrlEncode(userPwd, myEncoding) +
                //    "&" + HttpUtility.UrlEncode("pszMobis", myEncoding) +
                //    "=" + HttpUtility.UrlEncode(strMobile, myEncoding) +
                //    "&" + HttpUtility.UrlEncode("pszMsg", myEncoding) +
                //    "=" + HttpUtility.UrlEncode(noteContent, myEncoding) +
                //    "&" + HttpUtility.UrlEncode("iMobiCount", myEncoding) +
                //    "=" + HttpUtility.UrlEncode(mobileArray.Length.ToString(), myEncoding) +
                //    "&" + HttpUtility.UrlEncode("pszSubPort", myEncoding) +
                //    "=" + HttpUtility.UrlEncode("*", myEncoding) +
                //    "&" + HttpUtility.UrlEncode("MsgId", myEncoding) +
                //    "=" + HttpUtility.UrlEncode("1789", myEncoding);

                byte[] bytes = Encoding.UTF8.GetBytes(param);
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();



                var response = request.GetResponse();
                using (var reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")))
                {
                    string resultStr = reader.ReadToEnd();

                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.LoadXml(resultStr);
                    //XmlNode msgNode = xmlDoc.SelectSingleNode("string");
                    msg = xmlDoc?.InnerText ?? "";
                    if (msg.Length <= 15)
                    {
                        //发送失败 log
                        return false;
                    }
                    return true;
                }
            }
            catch (Exception e)
            {
                msg = "发送短信失败，接口连接失败，请联系管理员";
                return false;
            }
        }
    }
}
